<template>
  <div style="display: flex; justify-content: center; height: 40vh; width: 100vw; align-content: center">
    <el-card class="box-card" style="height: 400px; margin-top: 200px">
      <div class="title-box" >
        <div>用户登录</div>
      </div>

      <el-form ref="postForm" :model="postForm" :rules="loginRules">
        <el-form-item prop="name">
          <el-input
            v-model="postForm.name"
            style="width: 100%"
            placeholder="用户名"
            prefix-icon="el-icon-user"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="postForm.password"
            show-password
            style="width: 100%"
            placeholder="密码"
            type="password"
            prefix-icon="el-icon-lock"
          />
        </el-form-item>

        <el-form-item>
          <el-button :loading="loading" type="primary" style="width: 100%" @click.native.prevent="accountLogin">登录</el-button>
        </el-form-item>

      </el-form>

      <div style="display: flex; align-items: center; justify-content: flex-end">
        <el-link type="primary" disabled href="/#/register">立即注册</el-link>
      </div>
    </el-card>
    

  </div>

</template>

<script>
import request from '@/request'
import {md5} from '@/utils/md5'
import { setToken, setPerm } from '@/request/token'

export default {
  data() {
    return {
      loading: false,
      postForm: {
        name: 'root',
        password: 'root311'
      },
      loginRules: {
        name: [{ required: true, trigger: 'blur', message: '用户名不能为空' }], 
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }]
      }
    }
  },

  methods: {
    loginBack() {
      // 其它跳到主页
      this.$router.push({ name: 'Home' })

      setTimeout(function() {
        this.loading = false
      }, 1800)
    },

    accountLogin() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
			this.loading = true

			request({ method: 'post', url: `/login`, 
        data: {
          name: this.postForm.name,
          password: md5(this.postForm.password)
        } 
      }).then(resp=>{
				if(resp.data.code == '200'){
					var token = resp.data.data.token
					var perm = resp.data.data.perm
          setToken(token)
          setPerm(perm)
					if(token) this.loginBack()
				}else{
					this.$alert('账号或密码错误', '提示', {
						confirmButtonText: '确定',
					})
					this.postForm.password = ''
				}
			})
        }
      })
      this.loading = false
    }
  }
}
</script>
